package com.bytedance.lucky.security;

import com.alibaba.fastjson.JSONObject;
import com.bytedance.lucky.error.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author zouyaowen
 * @date 2021-02-14 00:57
 */
@Configuration
@Slf4j
@EnableWebSecurity
public class SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {


    @Autowired
    private TokenAuthenticationProvider tokenProvider;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers("/user/*");
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().cacheControl();
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .disable()
                .httpBasic().disable()
                .exceptionHandling().authenticationEntryPoint((req, res, e) -> {
            res.setContentType("application/json;charset=utf-8");
            JSONObject resData = new JSONObject();
            Object code = req.getAttribute(TokenFieldEnum.STATUS.getField());
            Object message = req.getAttribute(TokenFieldEnum.MESSAGE.getField());
            if (code != null && message != null) {
                resData.put(TokenFieldEnum.STATUS.getField(), code);
                resData.put(TokenFieldEnum.MESSAGE.getField(), message);
            } else {
                resData.put(TokenFieldEnum.STATUS.getField(), ExceptionEnum.AUTHENTICATION_ERROR.getStatus());
                resData.put(TokenFieldEnum.MESSAGE.getField(), ExceptionEnum.AUTHENTICATION_ERROR.getMessage());
            }
            res.getWriter().write(resData.toString());
        });
        AuthenticationManager authenticationManager = authenticationManager();
        TokenFilter filter = new TokenFilter(authenticationManager);
        http.authenticationProvider(tokenProvider);
        http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
